package cn.edu.hbwe.book.service;

import java.sql.SQLException;
import java.util.List;

import cn.edu.hbwe.book.dao.BookDao;
import cn.edu.hbwe.book.dao.OrderDao;
import cn.edu.hbwe.book.dao.OrderItemDao;
import cn.edu.hbwe.book.entity.OrderItem;
import cn.edu.hbwe.book.entity.Orders;
import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.utils.DataSourceUtils;

public class OrderService {
	private OrderDao odao = new OrderDao();
	private OrderItemDao oidao = new OrderItemDao();
	private BookDao bdao = new BookDao();

	// 1.添加订单
	public void addOrder(Orders order) {
		try {
			// 开启事务
			DataSourceUtils.startTransaction();
			// 向orders表中添加数据
			odao.addBook(order);
			// 2.2向orderItem表中添加数据
			oidao.addOrderItem(order);
			// 2.3修改商品表中数据.
			bdao.changeBookNum(order);
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				DataSourceUtils.rollback(); // 事务回滚
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				// 关闭，释放以及提交事务
				DataSourceUtils.releaseAndCloseConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 根据用户查找订单
	public List<Orders> findOrderByUser(User user) {
		List<Orders> orders = null;
		try {
			// 查找出订单信息
			orders = odao.findOrderByUser(user);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orders;
	}

	// 根据id查找订单
	public Orders findOrderById(String id) {
		Orders order = null;
		try {
			order = odao.findOrderById(id);
			List<OrderItem> items = oidao.findOrderItemByOrder(order);
			order.setOrderItems(items);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return order;
	}

	// 根据id删除订单 管理员删除订单
	public void delOrderById(String id) {
		try {
			DataSourceUtils.startTransaction();// 开启事务
			oidao.delOrderItems(id);
			odao.delOrderById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				DataSourceUtils.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				DataSourceUtils.releaseAndCloseConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 普通用户删除订单
	public void delOrderByIdWithClient(String id) {
		try {
			DataSourceUtils.startTransaction();// 开启事务
			// 从订单项中查找商品购买数量
			Orders order = new Orders();
			order.setId(id);
			List<OrderItem> items = oidao.findOrderItemByOrder(order);
			// 修改商品数量
			bdao.updateBookNum(items);
			oidao.delOrderItems(id); // 删除订单项
			odao.delOrderById(id); // 删除订单
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				DataSourceUtils.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				DataSourceUtils.releaseAndCloseConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 支付成功后修改订单状态
	public void updateState(String id) {
		try {
			odao.updateOrderState(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
